<template>
  <el-button type="success" @click="addUser">新增用户</el-button>
  <el-button type="primary" @click="downUserTemplate">用户模板</el-button>
  <el-button type="primary" @click="importUserByExcel">导入用户</el-button>
  <el-button type="primary" @click="exportUserByExcel">导出用户</el-button>
  <el-button type="danger" @click="batchDelUser">批量删除</el-button>
  <el-table :data="userList"
            style="width: 100%"
            class="table-content"
            @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"/>
    <el-table-column type="index" label="序号" width="80"/>
    <el-table-column prop="loginAct" label="账号" width="120"/>
    <el-table-column prop="name" label="姓名" width="120"/>
    <el-table-column prop="phone" label="手机" width="120"/>
    <el-table-column prop="email" label="邮箱" width="120"/>
    <el-table-column prop="createTime" label="创建时间" width="120"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" type="primary"
                   @click="showDetail(scope.row)">
          详情
        </el-button>
        <el-button
            size="small"
            type="success"
            @click="handleEdit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDel(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination background
                 :current-page="current"
                 :page-size="pageSize"
                 :page-sizes="[5, 10, 15, 20]"
                 :total="total"
                 layout="->, total,sizes,prev,pager,next,jumper"
                 @current-change="toPage"
                 @prev-click="toPage"
                 @next-click="toPage"
                 @size-change="handleSizeChange"/>

  <!--  展示编辑用户数据-->
  <el-dialog v-model="dialogFormVisible"
             width="55%"
             :title="this.userForm.id > 0 ? '编辑用户' : '新增用户'">
    <el-form
        :model="userForm"
        ref="userFormRef"
        label-width="auto"
        :rules="userRules"
    >
      <el-form-item label="账号" prop="loginAct">
        <el-input v-model="userForm.loginAct" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" prop="loginPwd">
        <el-input v-model="userForm.loginPwd" type="password" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="userForm.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="userForm.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-select v-model="userForm.accountNoExpired"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-select v-model="userForm.credentialsNoExpired">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="账号是否锁定" prop="accountNoLocked">
        <el-select v-model="userForm.accountNoLocked">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="账号是否启用" prop="accountEnabled">
        <el-select v-model="userForm.accountEnabled">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="userSubmit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

<!--  展示导入用户界面对话框-->
  <el-dialog v-model="showUserImportDialog" title="导入用户Excel" width="800">
    <el-upload
        ref="uploadExcelRef"
        class="upload-demo"
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :http-request="uploadFile"
    >
      <template #trigger>
        <el-button type="success">选择Excel文件</el-button>
      </template>
      重要提示：
      <ul>
        <li>上传文件仅支持后缀为.xls或.xlsx的文件；</li>
        <li>确认文件大小不超过50MB</li>
        <li>日期值以文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式</li>
      </ul>
      <el-button @click="showUserImportDialog = false">取消</el-button>
      <el-button type="primary" @click="submitExcel">
        提交
      </el-button>
    </el-upload>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/HttpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";
import {downloadUserTemplate, importUserExcel} from "../js/userView.js";

export default {
  name: "UserView",
  data() {
    return {
      // 展示的用户数据列表
      userList: [{}],
      current: 1,
      total: 0,
      pageSize: 5,
      dialogFormVisible: false,
      showUserImportDialog: false,
      options: [
        {value: 1, label: '是',},
        {value: 0, label: '否',},
      ],
      // 新增、编辑的用户数据
      userForm: [{}],
      userRules: {
        loginAct: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 1, max: 16, message: '长度应该为1-16位', trigger: 'blur'},
        ],
        loginPwd: [
          {required: false, message: '请输入密码', trigger: 'blur'},
          // {min: 1, max: 32, message: '长度应该为1-32位', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {
            min: 1, max: 16, message: '姓名必须是中文，且长度应该为1-16位', pattern: /^[\u4E00-\u9FA5]{1,5}$/,
            trigger: 'blur'
          }
        ],
        phone: [
          {required: true, message: '请输入电话', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, min: 1, max: 11, message: "手机号码格式有误", trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: "邮箱格式有误", min: 1, max: 32, trigger: 'blur'
          },
        ],
        accountNoExpired: [
          {required: true, message: '请输入账号是否未过期', trigger: 'blur'}
        ],
        credentialsNoExpired: [
          {required: true, message: '请输入密码是否未过期', trigger: 'blur'}
        ],
        accountNoLocked: [
          {required: true, message: '请输入账号是否未锁定', trigger: 'blur'}
        ],
        accountEnabled: [
          {required: true, message: '请选择账号是否可用', trigger: 'blur'}
        ],
        selVals: []
      }
    }
  },
  inject: ["reload", "age", "user"],
  mounted() {
    this.loadUserInfo(this.current, this.pageSize);
  },
  methods: {
    loadUserInfo(current, pageSize) {
      doGet("/api/users",
          {current: current, pageSize: pageSize}
      ).then(resp => {
        if (resp.data.code === 200) {
          this.total = resp.data.data.total;
          this.userList = resp.data.data.list;
        }
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.loadUserInfo(this.current, this.pageSize);
    },
    toPage(current) {
      this.current = current;
      this.loadUserInfo(current, this.pageSize);
    },
    handleSelectionChange(val) {
      let arr = [];
      val.forEach(item => {
        arr.push(item.id);
      })
      this.selVals = arr;
    },
    userSubmit() {
      this.$refs.userFormRef.validate(isValid => {
        let para = Object.assign({}, this.userForm);
        if (isValid) {
          this.dialogFormVisible = false;
          if (this.userForm.id > 0) {
            doPut("/api/user/edit", para)
                .then(resp => {
                  if (resp.data.code === 200) {
                    messageTip("修改成功", "success");
                    this.reload();
                  } else {
                    messageTip("修改失败", "error");
                  }
                })
          } else {
            doPost("/api/user/add", para).then(resp => {
              if (resp.data.code === 200) {
                messageTip("新增成功", "success");
                // 下面这种是全局刷新，建议使用局部刷新
                // this.loadUserInfo();
                // 局部刷新：采用DashBoard.vue中使用provide进行注册，该组件使用reject进行注入
                this.reload();
                console.log("注入后获得的age", this.age);
                console.log("注入后获得的user", this.user);
              } else {
                messageTip("新增失败", "error");
              }
            })
          }
        } else {
          console.log("提交的数据不合法");
        }
      })
    },
    // 新增用户
    addUser() {
      this.dialogFormVisible = true;
      if (this.userForm) {
        this.userForm = {};
        // 重置表单到初始值；
        // this.$nextTick(() => {
        //   如果修改对象的表单赋值没有放在nextTick中，就会在表单渲染时就会将这个修改对象作为初始值，所以出现无效了。使用nextTick保证表单在第一次渲染时是空值就可以了。
        //   this.$refs.userFormRef.resetFields();
        // });
      }
    },
    // 编辑用户
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.userForm = row;
    },
    // 删除用户
    handleDel(row) {
      messageConfirm("确定删除用户" + "【" + row.name + "】" + "吗？").then(
          doDelete("/api/user/del/" + row.id, {}).then(resp => {
            if (resp.data.code === 200) {
              messageTip("删除成功", "success");
              this.reload();
            } else {
              messageTip("删除失败", "error");
            }
          })
      ).catch(err => {
        messageTip("取消删除用户", "warning");
      })
    },
    // 批量删除数据
    batchDelUser() {
      console.log("this.selVals:", this.selVals);
      if (this.selVals === undefined || this.selVals.length <= 0) {
        messageTip("请选择需要删除的用户", "warning");
        return;
      }
      // 方法二：前端使用.join进行分割，后端使用.split进行划分
      let para = {selVals: this.selVals.join(",")};

      // 方法一：直接以字符串格式传递过去，后端使用.split进行划分
      // let para = {selVals: this.selVals.toString()};
      console.log("para", para);
      // messageConfirm("确认需要删除所选用户吗？").then(
      doDelete("/api/user/batchDel", para).then(resp => {
        if (resp.data.code === 200) {
          messageTip("批量删除成功", "success");
          this.reload();
        } else {
          messageTip("批量删除失败", "error");
        }
      })
      // ).catch(err=> {
      //   messageTip("取消批量删除用户", "warning");
      // })
    },
    // 展示详情数据
    showDetail(row) {
      this.$router.push("/dashboard/user/" + row.id);
    },
    // 下载用户模板
    downUserTemplate() {
      let params = {isBoolean: true};
      downloadUserTemplate(params).then(resp => {
        if (resp.data.code === 200) {
          messageTip("下载模板成功", "success");
        }else {
          messageTip("下载模板失败", "error");
        }
      }).catch(err => {
        debugger
        messageTip("下载模板失败", "error");
        console.log(err);
      })
    },
    // 导入用户
    importUserByExcel() {
      this.showUserImportDialog = true;
    },
    // 导出用户
    exportUserByExcel() {
      let params = {isBoolean: false};
      downloadUserTemplate(params).then(resp => {
        if (resp.data.code === 200) {
          messageTip("导出用户成功", "success");
        }else{
          messageTip("导出用户失败", "error");
        }
      }).catch(err => {
        messageTip("导出用户失败", "error");
        console.log(err);
      })
    },
    // 提交导入的用户excel数据
    submitExcel() {
      this.$refs.uploadExcelRef.submit();
    },
    // 真正执行提交文件的函数
    uploadFile(options) {
      // options.file.name
      let formData = new FormData();
      formData.append("file", options.file);
      importUserExcel(formData).then(resp => {
        if (resp.data.code === 200) {
          // 提交用户信息后，需要清空上一次导入的用户信息表
          this.$refs.uploadExcelRef.clearFiles();
          messageTip("导入用户成功", "success");
          this.showUserImportDialog = false;
          this.reload();
        }else {
          messageTip("导入用户失败", "error");
        }
      })
    },
    // file表示当前上传的文件，limit设为1表示只能上传一个，
    // filesList表示已上传的文件列表也会只有已上传的文件列表且长度为1
    handleExceed(files, filesList) {
      filesList.splice(1);
      messageTip("每次只能上传一个文件", "warning");
    }

  }
}
</script>

<style scoped>
.table-content {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>